'use client';

import Box from '@/app/[locale]/admin/common/box';
import { type PrefixedTTranslatedFields } from '@/lib/dictionaries';
import { useRouter } from 'next/navigation';
import useToast from '@/hooks/useToast';
import type { FormEvent } from 'react';
import { useMutation } from '@tanstack/react-query';
import { createNginxKey } from '@/services/api';
import Spinner from '@/app/[locale]/component/spinner/spinner';

export default function CreateNginxConfigKeyAdminPage(
  this: any,
  {
    translatedFields,
  }: {
    translatedFields: PrefixedTTranslatedFields<'logAdminPage'>;
  },
) {
  const { show } = useToast();
  const router = useRouter();

  const createNginxKeyMutation = useMutation(createNginxKey);

  async function onClickSave(e: FormEvent<HTMLFormElement>) {
    try {
      e.preventDefault();
      e.stopPropagation();

      await createNginxKeyMutation.mutateAsync({});

      show({
        type: 'SUCCESS',
        message: translatedFields.createCompleted,
      });

      setTimeout(() => {
        show({
          type: 'PRIMARY',
          message: translatedFields.returning,
        });
      }, 1000);

      setTimeout(() => {
        router.back();
      }, 1500);
    } catch (e) {
      createNginxKeyMutation.reset();
      show({
        type: 'DANGER',
        message: e,
      });
    }
  }

  return (
    <Box>
      <form onSubmit={onClickSave} className="vstack gap-4">
        <button
          type="submit"
          disabled={createNginxKeyMutation.isLoading}
          className="btn btn-success col col-lg-2 my-4"
        >
          {createNginxKeyMutation.isLoading && <Spinner classs="me-2" />}
          {translatedFields.createKey}
        </button>
      </form>
    </Box>
  );
}
